<?php

namespace App\Imports;

use App\Common\statement\CommonStatement;
use App\Exceptions\api\BaseException;
use App\Models\User;
use App\Models\user\Depart;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Concerns\ToCollection;

class UserSheetImport implements ToCollection
{
    public function collection(collection $rows)
    {
        $sex = array_flip(CommonStatement::sex);
//        DB::beginTransaction();
        try {
            $user_list = [];
            foreach ($rows as $k => $row) {
                $errorUser = [];
                if ($k != 0) {//跳过表头d
                    DB::beginTransaction();
                    $user = [
                        'name' => $row[1],
                        'nickname' => $row[1],
                        'password' => '12345678',
                        'phone' => (int)$row[2],
                        'sex' => $sex[$row[3]] ?? 1,
                        'level' => $row[4] == '是' ? 3 : ($row[5] == '是' ? 2 : 1),
                        'duty' => $row[8],
                        'cert_number' => $row[9]
                    ];
                    if (!$user['name']) {
                        DB::rollBack();
                        continue;

//                        throw new BaseException('导入失败:'.'-姓名不能为空');
                    }
//                    if(!$user['phone']){
//                        DB::rollBack();
//                        throw new BaseException('导入失败:'.'-手机号不能为空');
//                    }
                    if (!$row[6]) {
                        $errorUser[] = $user['name'];
                        DB::rollBack();
                        continue;
//                        throw new BaseException('导入失败:'.$user['name'].'-科室不能为空');
                    }
                    $departData = [
                        'pid' => 1,
                        'type' => 1,
                        'name' => str_replace(" ", "", $row[6])
                    ];
                    $depart = Depart::firstOrCreate($departData)->id;
                    $user['depart_id'][] = $depart;
                    if ($row[7]) {
                        $branchData = [
                            'pid' => 2,
                            'type' => 2,
                            'name' => str_replace(" ", "", $row[7])
                        ];
                        $branch = Depart::firstOrCreate($branchData)->id;
                        $user['branch_id'] = $branch;
                    }

                    $where = [
                        'name' => $user['name']
                    ];
                    if ($user->level = 3) {
                        $level3 = User::where('level', 3)->first();
                        if ($level3) {
                            $errorUser[] = $user['name'];
                            DB::rollBack();
                            continue;

//                            throw new BaseException('导入失败:主要领导仅能存在一个');
                        }
                    }
                    if ($user->level == 2) {
                        $depart_leader = User::where('level', 2)->where('depart_id', $user['depart_id'])->first();
                        if ($depart_leader) {
                            $depart = Depart::where('id', $user['depart_id'])->first();
                            $errorUser[] = $user['name'];
                            DB::rollBack();
                            continue;

//                            throw new BaseException('导入失败:'.$depart['name'].'-仅能存在一个领导');
                        }
                    }
                    if ($user->level == 1) {
                        $depart_leader = User::where('level', 2)->where('depart_id', $user['depart_id'])->first();
                        if (!$depart_leader) {
                            $depart = Depart::where('id', $user['depart_id'])->first();
                            $errorUser[] = $user['name'];
                            DB::rollBack();
                            continue;

//                            throw new BaseException('导入失败:'.$depart['name'].'-必须有且只有一个领导');
                        }
                    }
                    $userInfo = User::where($where)->first();
                    if ($userInfo) {
                        DB::rollBack();
                        continue;

//                        throw new BaseException('导入失败:'.$user['name'].'-姓名已存在,不能重复添加');
                    }
                    $add = User::create($user);
                    if (!$add) {
                        $errorUser[] = $user['name'];
                        DB::rollBack();
                        continue;
//                        throw new BaseException('导入失败:系统错误');
                    }
                    if ($add->level == 2) {
                        $depart_id_arr = explode(',', $add->depart_id);
                        Depart::where('leader_id', $add->id)->update(['leader_id' => null]);
                        foreach ($depart_id_arr as $item) {
                            $depart_leader = User::where('level', 2)
                                ->where('depart_id', $item)->first();
                            if ($depart_leader && $depart_leader['id'] != $add->id) {
                                User::where('id', $depart_leader['id'])->update(['level' => 1]);
                            }
                            Depart::where('id', $item)->update(['leader_id' => $add->id]);
                        }
                    }
                    DB::commit();
                }
            }
            if ($errorUser) {
                throw new BaseException('导入失败用户:' . implode(',', $errorUser));
            }
        } catch (\Exception $e) {
            DB::rollBack();
            throw new BaseException($e->getMessage());
        }

    }
}
